package pl.edu.pk.mech.kkbus.service;

import static pl.edu.pk.mech.kkbus.staticstrings.NameEntity.NAME_ENTITY_EXCHANGE_POINTS;

import java.util.Date;
import java.util.List;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;

import pl.edu.pk.mech.kkbus.component.ExternalEmailSender;
import pl.edu.pk.mech.kkbus.model.Award;
import pl.edu.pk.mech.kkbus.model.ExchangePoints;
import pl.edu.pk.mech.kkbus.model.User;
import pl.edu.pk.mech.kkbus.repository.ExchangePointsDAO;

public class ExchangePointsService {
    
    @Autowired
    ExchangePointsDAO exchangePointsDAO;
    
    @Autowired
    ExternalEmailSender emailSender;
    
    @Autowired
    UserService userService;
    
    @Autowired
    AwardService awardService;
    
    public boolean createOrExchange(ExchangePoints exchangePoints) {
    	
    	Award award = awardService.getAward(exchangePoints.getIdAward());
    	if (award != null) {
			int quantityTemp = award.getQuantity();
			quantityTemp = quantityTemp -1;
			award.setQuantity(quantityTemp);
			awardService.createOrUpdateAward(award);
		}else{
			return false;
		}
        
        User user = userService.getUser(exchangePoints.getIdUser());
        if (user == null) {
            return false;
        } else {
        	int userPoints = user.getPoints();
        	int awardPoint = award.getPoints();
            if (userPoints>0 && awardPoint <= userPoints) {
            	userPoints = userPoints - awardPoint;
            	user.setPoints(userPoints);
            	userService.updateUser(user);
			}
        }      
        
        exchangePoints.setHash(DigestUtils.md5Hex(String.valueOf(new Date()) + "pHe1Ux7kJA"));
        
        String message = "Zamówiłeś: "+ award.getName() +" Twój kod weryfikujący: " + exchangePoints.getHash();
        emailSender.send(user.getEmail(), "KKBus - Nagroda", message);
        
    	boolean result = exchangePointsDAO.createOrUpdate(exchangePoints, NAME_ENTITY_EXCHANGE_POINTS, exchangePointsDAO);
    
        return result ? true : false;
    }
    
    public ExchangePoints getAwardByHash(String hash) {
        return exchangePointsDAO.getAwardByHash(hash);
    }  
    
    public List<ExchangePoints> getAllExchangePoints() {
        return exchangePointsDAO.getAllExchangePoints();
    }  
}
